﻿using System;
using System.Xml;
using SS4U.Library;
using umbraco;

namespace SS4U.UiSearch.Dialog
{
    public partial class Search : umbraco.BasePages.UmbracoEnsuredPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Page.Form.DefaultButton = searchButton.UniqueID;

            if (!IsPostBack && helper.Request("search") != "")
            {
                keyword.Text = helper.Request("search");
                DoSearch();
            }
        }

        protected void search_Click(object sender, EventArgs e)
        {
            DoSearch();
        }

        private void DoSearch()
        {
            string query = keyword.Text.Trim();

            var searcher = new Searcher();
            var results = searcher.Search(query, null, "Umbraco Backend Search");

            var result = new XmlDocument();
            result.LoadXml("<results/>");
            foreach (var si in results)
            {
                var x = xmlHelper.addTextNode(result, "result", si.Text);
                x.Attributes.Append(xmlHelper.addAttribute(result, "id", si.Id.ToString()));
                x.Attributes.Append(xmlHelper.addAttribute(result, "icon", ""));
                x.Attributes.Append(xmlHelper.addAttribute(result, "title", si.Text));
                x.Attributes.Append(xmlHelper.addAttribute(result, "author", ""));
                x.Attributes.Append(xmlHelper.addAttribute(result, "changeDate", ""));
// ReSharper disable PossibleNullReferenceException
                result.DocumentElement.AppendChild(x);
// ReSharper restore PossibleNullReferenceException
            }
            searchResult.XPathNavigator = result.CreateNavigator();
        }
    }
}
